<?php 

namespace App\Repositories;
use Illuminate\Container\Container as App;
use App\Repositories\DepartmentRepository;
use App\Repositories\UserRepository;

class CustomerRepository extends Repository 
{
    public function __construct(App $app, DepartmentRepository $department, UserRepository $user) {
        parent::__construct($app); 
        $this->department = $department;
        $this->user = $user;
    }

    public function model() {
        return 'App\Models\Customer';
    }

    public function findIdsByname($name)
    {
    	return $this->model->where('name', 'like', "%{$name}%")->lists('id')->toArray();
    }

    public function findIdsByword($word)
    {
        return $this->model->where('name', 'like', "%{$word}%")->orWhere('domain', 'like', "%{$word}%")->lists('id')->toArray();
    }

    /**
     * @param int $perPage
     * @param array $columns
     * @return mixed
     */
    public function paginateList($where=[], $page = 20)
    {
        $model = $this->model->with('order', 'saler', 'saler.department', 'saler.region');
        $this->filterWhere($where, $model);

        return $model->orderBy('created_at', 'desc')->paginate($page);
    }

    // 搜索条件处理
    protected function filterWhere($where, $model)
    {
        $where = $where->filter(function ($item) { return $item; });

        $this->searchWord($where, $model);
        $this->searchDomain($where, $model);

        // 部门和员工
        foreach (['saler_id','department_id','region_id'] as $value) {
            if ($where->has($value)) {
                $funName = 'search_'.camel_case($value);
                $this->$funName($where->get($value), $model);
                break;
            }
        }

    }

    protected function searchWord($where, $model)
    {
        if ($where->has('word')) {
            $word = trim($where->get('word'));

            $model->where(function ($query) use ($word) {
                $query->where('name', 'like', "%{$word}%")->orWhere('domain', 'like', "%{$word}%");
            });
        }
    } 

    protected function searchDomain($where, $model)
    {
        if ($where->has('domain')) {
            $model->where('domain', 'like', '%'.$where->get('domain').'%');
        }
    } 

    protected function search_salerId($saler, $model)
    {
        $model->where('saler_id', $saler); 
    }

    protected function search_departmentId($department, $model)
    {
        $uids = $this->user->getUidsByDepartments($department);

        $model->whereIn('saler_id', $uids);
    }

    protected function search_regionId($region, $model)
    {
        $departments = $this->department->findIds($region);

        $this->search_departmentId($departments, $model);
    }

    /**
     * 批量更新客户所属的业务员
     *
     * @param  int|array $ids 客户信息ID
     * @param  int  $saler  业务员ID
     * @return Response
     */
    // 
    public function updateSaler($id, $salerId)
    {
        if (is_array($id)) {
            return $this->model->whereIn('id', $id)->update(['saler_id'=>$salerId]);
        }  

        return $this->update(['saler_id'=>$salerId], $id);
    }


    // 根据业务员得到客户的数量
    public function getCountsBySaler($id)
    {
        return $this->model->where('saler_id', $id)->count();
    }

    // 获取一个客户的详细信息
    public function getCustomerContractByName($name)
    {
        return $this->model->with('contracts')->where('name', $name)->first();
    }

    public function checkIsRegion(array $ids, $regionId)
    {
        $uids = $this->model->whereIn('id', $ids)->lists('saler_id');

        $regionIds = $this->user->getRegionsByUids($uids);
        $count = $regionIds->count();

        $errorMsg = '';

        if ($count > 1) {
            $errorMsg = '您没有权限转移部分客户。';
        } elseif ($count == 0) {
            $errorMsg = '您要转移的客户中，部分客户的没有业务员信息，请检查！';
        } elseif ($count == 1) {
           if ($regionIds->get(0) != $regionId) {
                $errorMsg = '您没有权限转移这些客户。';
           }
        }

        return $errorMsg;
    }
}